package com.taskmanager.controller;

import com.taskmanager.dto.LoginRequest;
import com.taskmanager.dto.RegisterRequest;
import com.taskmanager.dto.UserResponse;
import com.taskmanager.entity.User;
import com.taskmanager.service.UserService;
import com.taskmanager.util.ApiResponse;
import com.taskmanager.util.JwtUtil;
import com.taskmanager.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 * 处理用户注册、登录、登出等请求
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户注册
     * POST /api/user/register
     */
    @PostMapping("/register")
    public ApiResponse<UserResponse> register(@Validated @RequestBody RegisterRequest request) {
        try {
            UserResponse response = userService.register(request);
            return ResponseUtil.success("注册成功", response);
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("注册失败，服务器错误");
        }
    }
    
    /**
     * 用户登录
     * POST /api/user/login
     */
    @PostMapping("/login")
    public ApiResponse<UserResponse> login(@Validated @RequestBody LoginRequest request) {
        try {
            // 验证用户凭证
            User user = userService.login(request);
            
            // 生成JWT Token
            String token = jwtUtil.generateToken(user.getUserId(), user.getUsername());
            
            // 构建响应
            UserResponse response = new UserResponse();
            response.setUserId(user.getUserId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            response.setToken(token);
            
            return ResponseUtil.success("登录成功", response);
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("登录失败，服务器错误");
        }
    }
    
    /**
     * 用户登出
     * POST /api/user/logout
     */
    @PostMapping("/logout")
    public ApiResponse<Void> logout(HttpServletRequest request) {
        try {
            // 实际上JWT是无状态的，登出只需要前端删除Token即可
            // 这里可以记录登出日志或做其他处理
            Long userId = (Long) request.getAttribute("userId");
            System.out.println("用户 " + userId + " 登出");
            
            return ResponseUtil.success("登出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("登出失败");
        }
    }
    
    /**
     * 获取当前用户信息
     * GET /api/user/info
     */
    @GetMapping("/info")
    public ApiResponse<UserResponse> getUserInfo(HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            User user = userService.getUserById(userId);
            
            UserResponse response = new UserResponse();
            response.setUserId(user.getUserId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            
            return ResponseUtil.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("获取用户信息失败");
        }
    }
    
    /**
     * 验证Token是否有效
     * GET /api/user/validate
     */
    @GetMapping("/validate")
    public ApiResponse<Boolean> validateToken(HttpServletRequest request) {
        try {
            // 如果能到达这里，说明Token已经通过拦截器验证
            Long userId = (Long) request.getAttribute("userId");
            return ResponseUtil.success("Token有效", true);
        } catch (Exception e) {
            return ResponseUtil.error("Token无效");
        }
    }
}
